﻿using System.Runtime.Serialization;

namespace Vin.Tool.Core.EnumCategory;

public static class Extension
{
    public static (int, string) GetData(this Enum value)
    {
        var type = value.GetType();
        var name = Enum.GetName(type, value);
        return ((int)(dynamic)value, name ?? "");
    }

    public static string GetName(this Enum? value)
    {
        if (value == null) return "";
        var type = value.GetType();
        return Enum.GetName(type, value) ?? "";
    }

    public static T? GetCustomAttribute<T>(this Enum value) where T : Attribute
    {
        var type = value.GetType();
        var name = Enum.GetName(type, value);
        var field = type.GetField(name ?? "");
        return field?.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
    }

    public static T? GetCustomEnumAttribute<T>(this Enum value) where T : Attribute
    {
        var type = value.GetType();
        return type.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
    }

    public static string GetEnumMemberValue(this Enum value)
    {
        var member = value.GetCustomAttribute<EnumMemberAttribute>();
        return member?.Value ?? value.GetName();
    }
}